package com.zbw.weightlibrary.Activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import android_serialport_api.SerialPortFinder;
import androidx.appcompat.app.AppCompatActivity;

import com.zbw.weightlibrary.Connector.IBleControl;
import com.zbw.weightlibrary.Connector.IinfoCallback;
import com.zbw.weightlibrary.Connector.NewWeight;
import com.zbw.weightlibrary.Connector.WeightData;
import com.zbw.weightlibrary.R;
import com.zbw.weightlibrary.Util.WeightDataSave;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * 作者 ：jae
 * 时间 ：2019-02-26 11:31
 * 这个类是干嘛的？：麟罗串口电子称测试界面
 */

public class SerialConnectActivity extends AppCompatActivity implements IinfoCallback {
    private Button ButTest,ButGetWeight,ButBreak,ButComfirm;//初始化、获取重量、断开、确认
    private RelativeLayout rela_back;//返回
    private String[] baudrates;//波特率
    private String[] ports;//端口号
    private String selectPort;//选中端口号
    private int selectBaudrate;//选中波特率
    private static SerialPortFinder mSerialPortFinder;
    private TextView mTvWeight,tvTitle,tv_connectResult;
    private Spinner spSerialPort;
    private Spinner spBaudrate;
    private int SerialType;
    private IBleControl IControl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seri_lin_luo_main);
        setActivitySize(0.5, 0.6);//Activity大小
        // 隐藏系统通知栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        baudrates = this.getResources().getStringArray(R.array.baudrate);
        //控件初始化
        SerialType = getIntent().getIntExtra("key",NewWeight.WEIGHTSERIAL);
        selectPort = getIntent().getStringExtra("sp_serial_port");
        selectBaudrate = getIntent().getIntExtra("sp_serial_brate", 9600);
        initUI();
        initListener();
    }

    /**
     * 动态设置Activity的大小。
     */
    protected void setActivitySize(double width,double height) {
        //动态设置Activity的大小。
        Display display = getWindowManager().getDefaultDisplay(); // 为获取屏幕宽、高
        Point point = new Point();
        display.getSize(point);
        Window window = getWindow();
        WindowManager.LayoutParams windowLayoutParams = window.getAttributes(); // 获取对话框当前的参数值
        windowLayoutParams.width = (int) (point.x * width); // 宽度设置为屏幕的0.7
        windowLayoutParams.height = (int) (point.y * height); // 高度设置为屏幕的0.7
        windowLayoutParams.alpha = 1f;// 设置透明度
        getWindow().setAttributes(windowLayoutParams);
        //弹框式Activity设置圆角，注意：下面代码的顺序不可以改变，否则圆角效果设置不起效
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View view = getWindow().getDecorView();
        view.setBackgroundResource(R.drawable.activiy_corners_white);//圆角背景
    }

    private void initUI() {

        mTvWeight = (TextView) findViewById(R.id.tv_weight);
        tv_connectResult = (TextView) findViewById(R.id.tv_connectResult);
        ButTest = (Button) findViewById(R.id.ButTest);
        ButGetWeight = (Button) findViewById(R.id.ButGetWeight);
        ButBreak = (Button) findViewById(R.id.ButBreak);
        ButComfirm = (Button) findViewById(R.id.ButComfirm);
        rela_back = (RelativeLayout) findViewById(R.id.rela_back);

        //获取电子秤可使用的串口号
        try {
            ports = getSrialPortList();
            //加上商米设备的端口号【商米机自动获取的没有可用的端口号】
            ports= Arrays.copyOf(ports, ports.length+7);//数组扩容
            ports[ports.length-1] = "ttyHSL3";
            ports[ports.length-2] = "ttyHSL1";
            ports[ports.length-3] = "ttyHSL0";
            ports[ports.length-4] = "ttyS2";
            ports[ports.length-5] = "ttyS1";
            ports[ports.length-6] = "ttyS0";
            ports[ports.length-7] = "ttyS4";
            ports = testA(ports);//数组去重

        } catch (Exception e) {
            e.printStackTrace();
        }
        //串口路径初始化
        spSerialPort = (Spinner) findViewById(R.id.sp_port);
        ArrayAdapter arrayAdapter;
        if (ports != null) {
            arrayAdapter = new ArrayAdapter(this, R.layout.sp_tv_item, ports);
        } else {
            arrayAdapter = new ArrayAdapter(this, R.layout.sp_tv_item, new String[]{this.getString(R.string.str_no_serialport)});
        }
        spSerialPort.setAdapter(arrayAdapter);
        //波特率数据初始化
        spBaudrate = (Spinner) findViewById(R.id.sp_baudrate);
        ArrayAdapter portAdapter = new ArrayAdapter(this, R.layout.sp_tv_item, this.getResources().getStringArray(R.array.baudrate));
        spBaudrate.setAdapter(portAdapter);

        tvTitle=(TextView)findViewById(R.id.tv_title);
        tvTitle.setText("串口电子秤测试");

        if (ports != null) {
            // 设置默认值
            int spinnerPosition = Arrays.asList(ports).indexOf(selectPort);
            if (spinnerPosition >= 0) {
                spSerialPort.setSelection(spinnerPosition);
            }
        }

        // 设置默认值
        int baudratePosition = Arrays.asList(baudrates).indexOf((selectBaudrate+""));
        if (baudratePosition >= 0) {
            spBaudrate.setSelection(baudratePosition);
        }

    }

    //数组去重 方法一：通过list去重
    public static String[] testA(String [] arrStr) {
        List<String> list = new ArrayList<String>();
        for (int i=0; i<arrStr.length; i++) {
            if(!list.contains(arrStr[i])) {
                list.add(arrStr[i]);
            }
        }
        //返回一个包含所有对象的指定类型的数组
        String[] newArrStr =  list.toArray(new String[1]);
        return newArrStr;
    }

    private void initListener() {
        //波特率选择
        spBaudrate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //保存当前选择的波特率
                selectBaudrate = Integer.parseInt(baudrates[position]);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        //端口选择
        spSerialPort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (ports != null) {
                    selectPort = ports[position];
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        //初始化按键
        ButTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(IControl !=null) {
                    IControl.bleDisconnect();
                }
                WeightData weightData = new WeightData();
                weightData.setPort(selectPort);
                weightData.setBaudrate(selectBaudrate);
                IControl = NewWeight.getInstance().NewControl(SerialType,SerialConnectActivity.this,SerialConnectActivity.this,weightData);
                IControl.bleConnect();
            }
        });

        //获取重量按键
        ButGetWeight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(IControl !=null) {
                    IControl.getWeight();
                }else{
                    Toast.makeText(SerialConnectActivity.this,"请先初始化！",Toast.LENGTH_SHORT).show();
                }
            }
        });

        //断开连接按键
        ButBreak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //断开连接
                if(IControl !=null) {
                    IControl.bleDisconnect();
                    mTvWeight.setText("____ kg");
                    tv_connectResult.setText("");
                }else{
                    Toast.makeText(SerialConnectActivity.this,"请先初始化！",Toast.LENGTH_SHORT).show();
                }
            }
        });

        //确认按键
        ButComfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(IControl !=null) {
                    SaveData();
                    finish();
                }else{
                    Toast.makeText(SerialConnectActivity.this,"请先初始化！",Toast.LENGTH_SHORT).show();
                }
            }
        });

        //返回按键
        rela_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    //回调address数据
    private void SaveData() {
        //回传选中的波特率和端口号数据
        Intent intent = this.getIntent();
        intent.putExtra("sp_serial_port", selectPort);
        intent.putExtra("sp_serial_brate", selectBaudrate);
        this.setResult(-1, intent);
    }


    //获取设备端口号
    public String[] getSrialPortList() {
        mSerialPortFinder = new SerialPortFinder();
        ports = mSerialPortFinder.getAllDevices();
        String[] entriesReturn = new String[ports.length];
        for (int i = 0; i < ports.length; i++) {
            try {
                String[] strings = ports[i].split(" ");
                entriesReturn[i] = strings[0];
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return entriesReturn;
    }



    //连接设备
    @Override
    public void onConnect(final String str, final boolean is) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(is){
                    tv_connectResult.setText("连接设备成功");
                    ButTest.setText("断开");
                }else{
                    tv_connectResult.setText("连接设备失败");
                    ButTest.setText("初始化");
                }
            }
        });

    }
    //断开连接
    @Override
    public void onDisconnect(String str,boolean is) {
        //断开连接
        if (IControl != null) {
            IControl = null;
            mTvWeight.setText("____ kg");
            tv_connectResult.setText("");
        }
    }
    //获取重量
    @Override
    public void onGetWeight(final String String, final boolean isSta) {
        if(isFinishing()){
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isSta) {
                    mTvWeight.setText(java.lang.String.format("稳定：%skg", String));
                } else {
                    mTvWeight.setText(java.lang.String.format("未稳定：%skg", String));
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (IControl != null) {
            IControl.stopWeight();
            IControl.bleDisconnect();
            IControl = null;
        }
    }
}

